package com.valuegroup.smarttodo.ui.programme.goals;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.enums.FilterEnum;
import com.valuegroup.smarttodo.data.vo.AppCustomCfg;
import com.valuegroup.smarttodo.data.vo.GoalQueryParams;
import com.valuegroup.smarttodo.data.vo.GoalsItemVo;
import com.valuegroup.smarttodo.ui.programme.goals.detail.GoalsDetailActivity;
import com.valuegroup.smarttodo.plugins.flycotablayout.SlidingCommonTabLayout;
import com.valuegroup.smarttodo.plugins.flycotablayout.TabEntity;
import com.valuegroup.smarttodo.plugins.flycotablayout.listener.CustomTabEntity;
import com.valuegroup.smarttodo.plugins.flycotablayout.listener.OnTabSelectListener;
import com.valuegroup.smarttodo.util.Cfg;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 目标首页
 */
public class GoalsFragment extends Fragment {

    @BindView(R.id.btnExpand)
    LinearLayout btnExpand;
    @BindView(R.id.tagExpand)
    ImageView tagExpand;
    @BindView(R.id.expandable_layout)
    ExpandableLayout expandableLayout;
    @BindView(R.id.labCount)
    TextView labCount;

    @BindView(R.id.recycler_goals_list)
    RecyclerView recyclerView;

    @BindView(R.id.btnRange)
    SlidingCommonTabLayout btnRange;
    @BindView(R.id.btnYear)
    SlidingCommonTabLayout btnYear;
    @BindView(R.id.btnQuarter)
    SlidingCommonTabLayout btnQuarter;
    @BindView(R.id.btnMonth)
    SlidingCommonTabLayout btnMonth;

    private Unbinder unbinder;
    private GoalsAdapter adapter;
    private AppCustomCfg cfg;
    private GoalQueryParams queryParams;
    private int rangeTab, yearTab, quarterTab, monthTab;
    private boolean initFinish;

    public static GoalsFragment newInstance() {
        return new GoalsFragment();
    }

    public GoalsFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goals, container, false);
        unbinder = ButterKnife.bind(this, view);
        initFinish = true;


        // 初始参数
        cfg = Cfg.getCfg(getContext());
        queryParams = GoalQueryParams.getDefaultParams();

        initRecyclerView(view);
        initFilterTab();

        setHasOptionsMenu(true);
        return view;
    }


    private void initRecyclerView(View view) {
        adapter = new GoalsAdapter(view.getContext(), loadData());
        assert recyclerView != null;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
    }

    private ArrayList<CustomTabEntity> converTabEntity(List<String> tags) {
        ArrayList<CustomTabEntity> result = new ArrayList<>();
        for (int i = 0; i < tags.size(); i++) {
            String lab = tags.get(i).split("#")[0];

            // 用于判断tab选中
            int filter = Integer.parseInt(tags.get(i).split("#")[1].split("_")[0]);
            int value = Integer.parseInt(tags.get(i).split("#")[1].split("_")[1]);
            if (FilterEnum.RANGE_GOAL.getPosition() == filter && queryParams.getRange() == value) {
                rangeTab = i;
            } else if (FilterEnum.YEAR.getPosition() == filter && queryParams.getYear() == value) {
                yearTab = i;
            } else if (FilterEnum.QUARTER.getPosition() == filter && queryParams.getQuarter() == value) {
                quarterTab = i;
            } else if (FilterEnum.MONTHLY.getPosition() == filter && queryParams.getMonth() == value) {
                monthTab = i;
            }

            // 用于lab创建
            result.add(new TabEntity(lab, 0, 0));
        }
        return result;
    }

    private int convertVal(String key) {
        // 用于TAG展示(前缀+数值+后缀)#用于类型解析(数据类型)_用于类型解析(数值)
        return Integer.parseInt(key.split("#")[1].split("_")[1]);
    }

    private void initFilterTab() {

        List<String> rangeTags = ServiceFactory.getInstance().getFilterService().findGoalFilterTag(FilterEnum.RANGE_GOAL);
        List<String> monthTags = ServiceFactory.getInstance().getFilterService().findGoalFilterTag(FilterEnum.MONTHLY);
        List<String> quarterTags = ServiceFactory.getInstance().getFilterService().findGoalFilterTag(FilterEnum.QUARTER);
        List<String> yearTags = ServiceFactory.getInstance().getFilterService().findGoalFilterTag(FilterEnum.YEAR);

        btnRange.setTabData(converTabEntity(rangeTags));
        btnYear.setTabData(converTabEntity(yearTags));
        btnQuarter.setTabData(converTabEntity(quarterTags));
        btnMonth.setTabData(converTabEntity(monthTags));

        btnRange.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                btnQuarter.setVisibility(View.VISIBLE);
                btnMonth.setVisibility(View.VISIBLE);
                switch (position) {
                    case 0:
                        btnQuarter.setVisibility(View.GONE);
                        break;
                    case 1:
                        btnMonth.setVisibility(View.GONE);
                        break;
                    case 2:
                        btnQuarter.setVisibility(View.GONE);
                        btnMonth.setVisibility(View.GONE);
                        break;
                }
                queryParams.setRange(convertVal(rangeTags.get(position)));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnYear.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                queryParams.setYear(convertVal(yearTags.get(position)));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnQuarter.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                queryParams.setQuarter(convertVal(quarterTags.get(position)));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnMonth.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                queryParams.setMonth(convertVal(monthTags.get(position)));
                refreshAllData();
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        btnRange.setCurrentTab(rangeTab);
        btnYear.setCurrentTab(yearTab);
        btnQuarter.setCurrentTab(quarterTab);
        btnMonth.setCurrentTab(monthTab);

        btnYear.showDot(yearTab);
        btnQuarter.showDot(quarterTab);
        btnMonth.showDot(monthTab);
        btnYear.getMsgView(yearTab).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorLink));
        btnQuarter.getMsgView(quarterTab).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorLink));
        btnMonth.getMsgView(monthTab).setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorLink));

        btnQuarter.setVisibility(View.GONE);
    }


    @OnClick({R.id.btnExpand})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnExpand:
                if (expandableLayout.isExpanded()) {
                    tagExpand.setImageResource(R.drawable.ic_expand_gray3);
                    expandableLayout.collapse();
                } else {
                    expandableLayout.expand();
                    tagExpand.setImageResource(R.drawable.ic_shrink_gray3);
                }
                break;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //先clear()一下, 这样按钮就只有Fragment中设置的自己的了, 不会有Activity中的按钮.
        menu.clear();
        inflater.inflate(R.menu.menu_goal, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.menu_goals_2).setTitle(!cfg.isGoalHideFinish() ? R.string.goals_m2 : R.string.goals_m2_o);
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.menu_goals_1:
                startActivityForResult(new Intent(getContext(), GoalsDetailActivity.class), 1003);
                break;
            case R.id.menu_goals_2:
                // 隐藏已完成项
                cfg.setGoalHideFinish(!cfg.isGoalHideFinish());
                Cfg.saveCfg(getContext(), cfg);
                refreshAllData();
                break;
        }
        return true;
    }

    /**
     * 读取所有数据
     */
    private List<GoalsItemVo> loadData() {
        queryParams.readCfg(cfg);
        List<GoalsItemVo> datas = ServiceFactory.getInstance().getGoalsService().findGoalForHome(queryParams);

        setLabCount(datas);
        return datas;
    }

    private void setLabCount(List<GoalsItemVo> datas) {
        int finish = 0;
        for (GoalsItemVo v : datas) {
            if (v.isShowFinish()) {
                finish++;
            }
        }

        labCount.setText(String.format(getResources().getString(R.string.goal_count_lab), finish, datas.size()));
    }

    /**
     * 更新列表中某条数据
     * 没有指定的刷新内容时，刷新整个列表
     *
     * @param intent
     */
    private void refreshData(Intent intent) {
        if (intent == null) {
            refreshAllData();
            return;
        }

        long id = intent.getLongExtra(GoalsDetailActivity.PARAMS_KEY, 0);
        int position = intent.getIntExtra(GoalsDetailActivity.PARAMS_POSITION, 0);

        if (id == 0) {
            refreshAllData();
            return;
        }

        // 刷新列表中当前操作记录
        GoalsItemVo data = ServiceFactory.getInstance().getGoalsService().getGoalsItemVo(id);
        adapter.refreshData(position, data);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(position);
    }

    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    class GoalsAdapter extends CommonRecyclerAdapter<GoalsItemVo> {

        GoalsAdapter(Context context, List<GoalsItemVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_goals);
            setBottomLayoutId(R.layout.item_default_bottom);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {
            GoalsItemVo data = getData(position);

            // 详情页跳转
            LinearLayout rootLayout = v.getView(R.id.rootLayout);
            rootLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), GoalsDetailActivity.class);
                    intent.putExtra(GoalsDetailActivity.PARAMS_KEY, data.getId());
                    intent.putExtra(GoalsDetailActivity.PARAMS_POSITION, position);
                    startActivityForResult(intent, 1001);
                }
            });

            // 完成状态控制
            if (data.isShowFinish()) {
                v.setViewVisibility(R.id.tagFinish, data.isShowFinish());
                //v.setTextAndColor(R.id.labTitle, data.getLabTitle(), ContextCompat.getColor(getContext(), R.color.textAccent));
                v.setViewVisibility(R.id.tagGrow, false);
            } else {
                v.setViewVisibility(R.id.tagFinish, data.isShowFinish());
                //v.setTextAndColor(R.id.labTitle, data.getLabTitle(), ContextCompat.getColor(getContext(), R.color.textDefault));
                v.setViewVisibility(R.id.tagGrow, true);
                v.setImageResource(R.id.tagOrientation, data.getLabGrow() > 0 ? R.drawable.ic_up_red : R.drawable.ic_down_green);
                v.setText(R.id.labGrow, String.valueOf(data.getLabGrow()));
            }
            v.setViewVisibility(R.id.tagStart, data.isShowStar());
            v.setViewVisibility(R.id.labBranch, data.isShowBranch());
            v.setText(R.id.labTitle, data.getLabTitle());
            v.setText(R.id.labBranch, data.getLabBranch());
            v.setText(R.id.labDate, data.getLabRange());
        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
